package com.sctvcloud.zhaohua_sd.ui.activities;

import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.haibin.calendarview.CalendarView;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Constances;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.beans.FUsers;
import com.sctvcloud.zhaohua_sd.beans.IntegralAddBean;
import com.sctvcloud.zhaohua_sd.beans.SignInfo;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.http.ParamsEditor;
import com.sctvcloud.zhaohua_sd.ui.utils.TitleUtils;
import com.sctvcloud.zhaohua_sd.utils.UserManager;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class SignInActivity extends BaseActivity {

    @BindView(R.id.sign_in_rule_description)
    protected TextView ruleDescription;
    @BindView(R.id.sign_in_date)
    protected TextView tvDate;
    @BindView(R.id.sign_in_tip_days)
    protected TextView tvSignDays;
    @BindView(R.id.sign_in_calendar)
    protected CalendarView calendarView;

    private final String Key_Pre = "pre_sign_in";

    private boolean isTesttting = false;//是否使用测试数据

    private int todayDay = -1;

    private int signedSize = -1;
    private int lastSignDay = -1;
    private SignInfo signInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle("签到");
        init();
    }

    @Override
    protected void initInject() {
        initButterknifeBiner(R.layout.activity_sign_in);
    }

    private void init() {
        SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.sign_date_format));
        tvDate.setText(sdf.format(new Date(System.currentTimeMillis())));
        Calendar c = Calendar.getInstance();
        int day = c.get(Calendar.DAY_OF_MONTH);
        final int year = c.get(Calendar.YEAR);
        final int month = c.get(Calendar.MONTH);
        String today = DateUtils.formatDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd");
        if (shouldSignToday(today)) {
            signInToday(today, day);
        }
        calendarView.setOnlyCurrentMode();
        calendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() {
            @Override
            public void onMonthChange(int y, int m) {
                tvDate.setText(y + "年" + m + "月");
            }
        });
        getSignedData();
    }

    private boolean shouldSignToday(String today) {
        String pre = SharedPreferencesUtil.getSharedPreferenceInstance(this).getString(Key_Pre, "");
//        if (TextUtils.isEmpty(pre)) {
//            return true;
//        }
//        if (pre.startsWith("test")) {
//            if (isTesttting) {
//                pre = pre.replace("test", "");
//            }else {
//                return true;
//            }
//        }else {
//            return isTesttting || !TextUtils.equals(pre, today);
//        }
//        return !TextUtils.equals(pre, today);//如果不想使用此方式，可用下面注释掉的方式
        return TextUtils.isEmpty(pre) || !TextUtils.equals(pre, today);
    }

    private void signInToday(String todayStr, int todayInt) {
        ParamsEditor pe = new ParamsEditor();
        pe.put("ruleType", Constances.ADD_INTEGRAL_SIGN_IN);
        pe.put("token", UserManager.getInstance().getToken());
        pe.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
        NetUtils.getNetAdapter().postAddIntegral(getOwnerName(), pe.getEncryptedParams(null)
                , new AbsNetCallBack<IntegralAddBean>(IntegralAddBean.class, todayStr, todayInt) {
                    @Override
                    public void onSuc(IntegralAddBean iab) {
                        if (iab != null && iab.getRuleType() == Constances.ADD_INTEGRAL_SIGN_IN) {
//                            Cache.getInstance().getUserInfo().addIntegral(iab.getIntegral());//这里需要使用，为了测试注释掉的，后期可能会先获取用户信息
                            toastInCenter(getString(R.string.sign_suc_format, iab.getIntegral()));
//                            SharedPreferencesUtil.setParams(SignInActivity.this, Key_Pre, (String) obj);//暂时注释掉用以测试
                            todayDay = int1;
                            if (signInfo != null) {
                                List<Integer> days = signInfo.getSignInInfo();
                                days.add(todayDay);
                                freshSignDays(days);
                            }
                        }
//                        freshSignDays(-1, -1);
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg, int netCode) {
                        super.onError(ex, errorMsg, netCode);
                        if (isTesttting) {
                            if (netCode == 401) {
                                IntegralAddBean iab = new IntegralAddBean();
                                iab.setRuleType(Constances.ADD_INTEGRAL_SIGN_IN);
                                iab.setIntegral((int) (Math.random() * 4 + 3));
                                onSuc(iab);
                            } else {
                                freshSignDays(null);
                            }
                        } else {
                            freshSignDays(null);
                        }
                    }

                    @Override
                    public boolean whenLoginExpiredBackGround() {//正常测试时删除此方法
                        return true;
                    }
                });
    }

    private void getSignedData() {
        FUsers fu = UserManager.getInstance().getUser();
        NetUtils.getNetAdapter().getSignInfo(getOwnerName(), fu.getPhoneNumber(), fu.getToken(), new AbsNetCallBack<SignInfo>(SignInfo.class) {

            Map<String, com.haibin.calendarview.Calendar> map;

            @Override
            public void onSuc(SignInfo si) {
                signInfo = si;
                if (map != null) {
                    calendarView.setSchemeDate(map);
//                    tvSignDays.setText(map.size() + "");
                }
                if (si != null) {
                    if (!TextUtils.isEmpty(si.getDescribe())) {
                        ruleDescription.setText(si.getDescribe());
                    }
                    if (ListUtils.isListValued(si.getSignInInfo())) {
//                        int size = si.getSignInInfo().size();
                        freshSignDays(si.getSignInInfo());
                    } else {
                        freshSignDays(null);
                    }
                } else {
                    freshSignDays(null);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
                if (isTesttting) {
                    map = initTestingSchemes(calendarView.getCurDay());
                    onSuc(null);
                } else {
                    freshSignDays(null);
                }
            }

            @Override
            public SignInfo doInBackground(SignInfo si) {
                if (si != null) {
                    map = initScheme(si.getSignInInfo());
                }
                return super.doInBackground(si);
            }

            @Override
            public boolean whenLoginExpiredBackGround() {//正常测试时删除此方法
                return isTesttting;
            }
        });
    }

    private Map<String, com.haibin.calendarview.Calendar> initScheme(List<Integer> s) {
        if (!ListUtils.isListValued(s)) {
            return null;
        }
        int year = calendarView.getCurYear();
        int month = calendarView.getCurMonth();
        Map<String, com.haibin.calendarview.Calendar> map = new HashMap<>();
        for (int i = 0; i < s.size(); i++) {
            com.haibin.calendarview.Calendar c = getSchemeCalendar(year, month, s.get(i), 0xF75C43, "记");
            map.put(c.toString(), c);
        }
        return map;
    }

    private synchronized void freshSignDays(int last, int size) {
        String str = "0";
        if (last == -1 || size == -1) {
            if (signedSize >= 0) {
                if (todayDay > 0 && lastSignDay != todayDay) {
                    str = signedSize + 1 + "";
//                    tvSignDays.setText(signedSize + 1 + "");
                } else {
                    str = signedSize + "";
//                    tvSignDays.setText(signedSize + "");
                }
            } else {
                if (todayDay > 0) {
                    str = "1";
//                    tvSignDays.setText("1");
                }
            }
        } else {
            if (todayDay > 0) {
                if (last != todayDay) {
                    str = size + 1 + "";
                } else {
                    str = size + "";
                }
            } else {
                if (size >= 0) {
                    str = size + "";
                }
            }
        }
        tvSignDays.setText(str);
    }

    private synchronized void freshSignDays(List<Integer> s) {

        int maxCount = 1;
        int curCount = 1;
        if (null != s) {
            for (int i = 0; i < s.size(); i++) {
                if (i < s.size() - 1) {
                    if (s.get(i) + 1 == s.get(i + 1)) {
                        curCount++;
                    } else {
                        if (curCount > maxCount) {
                            maxCount = curCount;
                        }
                        curCount = 1;
                    }
                } else {
                    maxCount = curCount > maxCount ? curCount : maxCount;
                }
            }
        }
        tvSignDays.setText(String.valueOf(maxCount));
    }

    private com.haibin.calendarview.Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        com.haibin.calendarview.Calendar calendar = new com.haibin.calendarview.Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }

    private Map<String, com.haibin.calendarview.Calendar> initTestingSchemes(int today) {
        if (today == 1) {
            return null;
        }
        int size = 1;
        if (today > 2) {
            size = (int) (Math.random() * (today - 1) + 1);
        }
//        size=19;
        int year = calendarView.getCurYear();
        int month = calendarView.getCurMonth();
        int start = 0;
//        int len = today;
//        int lave = size;
        Map<String, com.haibin.calendarview.Calendar> map = new HashMap<>();
        for (int i = 0; i < size; i++) {
//            if (len > start) {
//                len -= start;
//            } else {
//                len = 0;
//            }
            int len = today - start - 1;
            start += (int) (Math.random() * (len / (size - i)) + 1);
            JLog.e("ddddd  size=" + size + "  today=" + today + "\nstart=" + start + "  len=" + len + "  lave=" + (size - i)
                    + "  i=" + i);
            com.haibin.calendarview.Calendar c = getSchemeCalendar(year, month, start, 0xFFedc56d, "记");
            map.put(c.toString(), c);
        }
        return map;
    }

}
